<?php

namespace app\repository;

use app\popo\model\Employee;
use app\support\ListContainer;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;

class EmployeeRepository
{
    /**
     * @param string $username
     * @return Employee|null
     */
    public function getByUsername(string $username): Employee|null
    {
        return Employee::query()->where("username", $username)->first();
    }

    public function listOf(array $employeePageQueryDTO): ListContainer
    {
        $name = Arr::get($employeePageQueryDTO, "name");
        $page = Arr::get($employeePageQueryDTO, "page");
        $pageSizee = Arr::get($employeePageQueryDTO, "pageSize", 20);

        $employees = Employee::query()->when($name, function (Builder $builder) use ($name){
            $builder->where("name", "like", "%$name%");
        });

        $paginate = $employees->paginate($pageSizee);

        return new ListContainer($paginate, function (Employee $employee) {
            return [
                "id" => $employee->id,
                "name" => $employee->name,
                "username" => $employee->username,
                "password" => $employee->password,
                "phone" => $employee->phone,
                "sex" => $employee->sex,
                "idNumber" => $employee->id_number,
                "status" => $employee->status,
                "createTime" => $employee->create_time->format("Y-m-d H:i:s"),
                "updateTime" => $employee->update_time->format("Y-m-d H:i:s"),
            ];
        });
    }
}